import {
  findByCity, getProjectPermission, changeStatus, editFun, deleteFun, deleteHexin, findByPro, getProjectByCompet, exportXls
} from './weekReportServ'
import { request } from 'config/request'
// import { parse } from 'qs'
import { message } from 'antd'
// import moment from 'moment'
import $ from 'jquery'
import config from 'config/config'
import axios from 'axios'
import { rstr2b64 } from '../../../../utils/md5'
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'

const defultState = {
  btnLoading: false,
  biz: {
    queryForm: {}
  },
  biz1: {
    queryForm: {}
  },
  biz2: {
    queryForm: {}
  },
  biz3: {
    queryForm: {}
  },
  url: '',
  tabsType: '',
  areaList: [],
  products: [],
  productList: [],
  distributionNameList: [],
  cityList: [],
  id: "",
  visible: false,
  detail: {
    detail: ''
  }
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
          dispatch({ type: 'getProjectPermission', payload: { tabsType: query.tabsType } })
        }
      })
    },
  },

  effects: {
    *clickExport({ payload }, { put, select, call }){
      if(payload.item.status=='0'){
        return message.warning('请先发布再导出');
      };
        request({
          url: `${config.aheadPlan}admin/groupWeekly/groupWeekly/exportPDF?id=${payload.item.id}`,
          method: 'get',
        }).then(function(res){
          let {result}=res;
          let {message,title}=result;
          var saveAs = function (blob, filename) {
            var URL = window.URL || window.webkitURL;
            var type = blob.type;
            var force_saveable_type = 'application/octet-stream';
            if (type && type != force_saveable_type) { // 强制下载，而非在浏览器中打开
              var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
              blob = slice.call(blob, 0, blob.size, force_saveable_type);
            }
            var url = URL.createObjectURL(blob);
            var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            save_link.href = url;
            save_link.download = filename;
    
            var event = new MouseEvent("click", {
              bubbles: true,
              cancelable: true,
              view: window
            });
            save_link.dispatchEvent(event);
            URL.revokeObjectURL(url);
          }
          var oReq = new XMLHttpRequest();
          var URLToPDF = message;
            oReq.open("GET", URLToPDF, true);
            oReq.responseType = "blob";
            oReq.onload = function () {
              var file = new Blob([oReq.response], { type: 'application/pdf' });
              console.log(oReq.response,'123')
              saveAs(file, title+'.pdf');
            };
            oReq.send();
        });
    },
    *getProjectPermission({ payload }, { put, select, call }) {
      let { areaList, tabsType } = yield select(state => state[tmpModule.namespace])
      let subElements = JSON.parse(localStorage.navBar).subElements
      if (subElements.includes(170401)) {
        tabsType = '1'
      }
      if (!subElements.includes(170401) && subElements.includes(170402)) {
        tabsType = '2'
      }
      if (!subElements.includes(170401) && !subElements.includes(170402) && subElements.includes(170403)) {
        tabsType = '3'
      }
      if (payload.tabsType) {
        tabsType = payload.tabsType
      }
      let params = {
        userId: localStorage.username
      }
      const { success, projectCityList } = yield call(getProjectPermission, { ...params })
      areaList = projectCityList.map((item, index) => {
        return {
          label: item.areaName,
          value: item.areaId,
          children: item.cityList
        }
      })
      yield put({
        type: 'updateStore',
        payload: { areaList, tabsType }
      })
      if (subElements.includes(170401)) {
        $(".configuration-center-tabs .ant-tabs-tab").eq(0).css('display', 'inline-block');
      } else {
        $(".configuration-center-tabs .ant-tabs-tab").eq(0).css('display', 'none');
      }
      if (subElements.includes(170402)) {
        $(".configuration-center-tabs .ant-tabs-tab").eq(1).css('display', 'inline-block');
      } else {
        $(".configuration-center-tabs .ant-tabs-tab").eq(1).css('display', 'none');
      }
      if (subElements.includes(170403)) {
        $(".configuration-center-tabs .ant-tabs-tab").eq(2).css('display', 'inline-block');
      } else {
        $(".configuration-center-tabs .ant-tabs-tab").eq(2).css('display', 'none');
      }
    },
    *findByProject({ payload }, { put, select, call }) {
      let { products, cityList } = yield select(state => state[tmpModule.namespace])
      cityList.map((item, index) => {
        if (item.value == payload.cityid) {
          item.projectList.map((ele) => {
            ele.label = ele.projectName;
            ele.value = ele.projectId;
          });
          console.log(item, 'aaaa')
          products = item.projectList;
        }
      });
      yield put({ type: 'updateStore', payload: { products } })
    },
    *findByCity({ payload }, { put, select, call }) {
      let { cityList } = yield select(state => state[tmpModule.namespace])
      let params = {
        area: payload.areaId,
      }
      const { success, result } = yield call(findByCity, { ...params })
      if (success) {
        let list = result.filter(item => !!item)
        cityList = list.map((item, index) => {
          return {
            label: item.city,
            value: item.cityid,
            projectList: item.projectList
          }
        })
        yield put({
          type: 'updateStore',
          payload: { cityList }
        })
      }
    },
    *deleteFun({ payload }, { put, select, call }) {
      if (payload.type == "竞品") {
        let params = {
          id: payload.params.id,
          begintime: payload.params.begintime,
          endtime: payload.params.endtime,
        }
        const { success, msg, data } = yield call(deleteFun, params)
        let defultState = yield select(state => state[tmpModule.namespace])
        if (success) {
          message.success('操作成功')
          defultState.biz1.refreshListDatas(true)
        }
      }
      if (payload.type == "核心") {
        let params = {
          id: payload.params.id
        }
        const { success, msg, data } = yield call(deleteHexin, params)
        let defultState = yield select(state => state[tmpModule.namespace])
        if (success) {
          message.success('操作成功')
          defultState.biz3.refreshListDatas(true)
        }
      }
    },
    *findByPro({ payload }, { put, select, call }) {
      let { productList } = yield select(state => state[tmpModule.namespace])
      let params = {
        areaId: payload.areaId
      }
      const { success, msg, result } = yield call(findByPro, params)
      let defultState = yield select(state => state[tmpModule.namespace])
      if (success) {
        productList = result.map((item, index) => {
          return {
            label: item.projectName,
            value: item.projectId,
          }
        })
        yield put({ type: 'updateStore', payload: { productList } })
      }
    },
    *getProjectByCompet({ payload }, { put, select, call }) {
      let { distributionNameList } = yield select(state => state[tmpModule.namespace])
      let params = {
        project: payload.productId
      }
      const { success, result } = yield call(getProjectByCompet, { ...params })
      if (success) {
        distributionNameList = result.map((item, index) => {
          return {
            label: item.competName,
            value: item.competName,
          }
        })
        yield put({ type: 'updateStore', payload: { distributionNameList } })
      }
    },
    *exportXls({ payload }, { put, select, call }) {
      let { biz3, biz1 } = yield select(state => state[tmpModule.namespace])
      let tempParams = {}
      let tempUrl = ''
      if (payload.type == '核心') {
        tempParams = { ...biz3.queryForm }
        tempUrl = `${config.aheadPlan}coreCompet/corecompet/exportXls`
      }
      if (payload.type == '竞品') {
        tempParams = { ...biz1.queryForm }
        tempUrl = `${config.aheadPlan}admin/competitorWeekly/competitorWeekly/exportXls`
      }
      axios({
        method: 'post',
        url: tempUrl,
        responseType: 'blob',
        headers: {
          "X-Pc-Token": localStorage.getItem("username") + ',' + new Date().getTime() + ',' + rstr2b64(localStorage.getItem("username") + ',' + new Date().getTime())
        },
        data: tempParams,
      }).then(res => {
        const content = res.data
        const blob = new Blob([content])
        Date.prototype.Format = function (fmt) { // author: meizz
          var o = {
            "M+": this.getMonth() + 1, // 月份
            "d+": this.getDate(), // 日
            "h+": this.getHours(), // 小时
            "m+": this.getMinutes(), // 分
            "s+": this.getSeconds(), // 秒
            "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
            "S": this.getMilliseconds() // 毫秒
          };
          if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
          for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          return fmt;
        }
        let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
        let fileName = payload.type == '核心' ? `核心竞品 ${dateTime}.xls` : `竞品周报 ${dateTime}.xls`
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        message.success('导出成功')
      })
    },
    *submitContent({ payload }, { put, select, call }) {
      let { btnLoading, biz1 } = yield select(state => state[tmpModule.namespace])
      if (payload.type == "集团") {
        let params = {
          id: payload.params.id,
          status: payload.params.status == '1' ? '0' : '1',
          updateBy: localStorage.nickname,
          updateUser: localStorage.username,
          startTime: payload.params.startTime,
          endTime: payload.params.endTime,
          title: payload.params.title,
        }
        const { success, msg, data } = yield call(changeStatus, { ...params })
        let defultState = yield select(state => state[tmpModule.namespace])
        if (success) {
          message.success('操作成功')
          defultState.biz2.refreshListDatas(true)
        }
      }
      if (payload.type == "竞品") {
        let params = {
          id: payload.params.id,
          weeklystatus: payload.params.weeklystatus == '1' ? '0' : '1',
          updateBy: localStorage.nickname,
          updateUser: localStorage.username
        }
        const { success, msg, data } = yield call(editFun, { ...params })
        let defultState = yield select(state => state[tmpModule.namespace])
        if (success) {
          message.success('操作成功')
          defultState.biz1.refreshListDatas(true)
        }
      }
      if (payload.type == "多选提交") {
        if (biz1.selectedRows.length == 0) {
          message.warning('请先选择要提交的数据')
          return
        }
        let arr = []
        for (var item of biz1.selectedRows) {
          arr.push(item.id)
        }
        let params = {
          id: arr.join(','),
          weeklystatus: '1',
          updateBy: localStorage.nickname,
          updateUser: localStorage.username
        }
        btnLoading = true
        yield put({ type: 'updateStore', payload: { btnLoading } })

        const { success, msg, data } = yield call(editFun, { ...params })
        let flag = success.toString()
        if (flag) {
          btnLoading = false
          yield put({ type: 'updateStore', payload: { btnLoading } })
        }
        let defultState = yield select(state => state[tmpModule.namespace])
        if (success) {
          message.success('操作成功')
          defultState.biz1.refreshListDatas(true)
        }
      }
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule

